﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PhoneRater
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.callsTableAdapter.Fill(this.mainFormDataSet.Calls);
        }
        private void _btShowReferences_Click(object sender, EventArgs e)
        {
            var form = new ReferenceBooksForm();
            form.ShowDialog();
        }

        private void _btShowEmploeesPhones_Click(object sender, EventArgs e)
        {
            var form = new EmployeesPhonesForm();
            form.ShowDialog();
        }

        private void BtCalculateClick(object sender, EventArgs e)
        {
            var form = new CalculateForm();
            form.ShowDialog();
        }

        private bool _onlyDigits(string st)
        {
            foreach (char c in st) { if (!char.IsDigit(c)) return false; }
            return true;
        }

        private void LogParsing(string fn)
    {
            string[] lines = System.IO.File.ReadAllLines(fn);
            char[] brakets = {'[', ']'};
            char[] space = {' '};
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i][0] != '+') continue;
                string[] columns = lines[i].Split(space,StringSplitOptions.RemoveEmptyEntries);
                if (columns[8].Length > 4 || !_onlyDigits(columns[8])) continue;
                string[] destNumbers = columns[7].Split(brakets);
                if (destNumbers.Length==1 || destNumbers[1].Length < 7 
                     || !_onlyDigits(destNumbers[1])) continue;
                destNumbers[1]=destNumbers[1].TrimStart('9');
                if (columns[8].Length == 4 || columns[8].Length == 3)
                {
                    int internalNumber = int.Parse(columns[8]);
                    if (columns[8].Length == 4) internalNumber -= 6000;
                    DateTime timeStamp = Convert.ToDateTime(columns[4] + ' ' + columns[5]);
                    string[] durationString = columns[6].Split(':');
                    int duration = int.Parse(durationString[0])*3600 + 
                                    int.Parse(durationString[1])*60 + 
                                     int.Parse(durationString[2]);
                    if (!_onlyDigits(columns[3])) // звонок ушел на сервер
                    {  //пошли искать ответную строку с сервера в линию

                        int j = i + 1;  // может следующая ?
                        columns = lines[j].Split(space, StringSplitOptions.RemoveEmptyEntries);
                        string[] destNumbers2 = columns[7].Split(brakets);
                        if (destNumbers2.Length == 1 || destNumbers2[1] != destNumbers[1] ||
                            !_onlyDigits(columns[3]) )  // не нашлась строка с тем же набранным номером
                        {
                            j = i - 1;  // тогда может предыдущая ?
                            columns = lines[j].Split(space, StringSplitOptions.RemoveEmptyEntries);
                            destNumbers2 = columns[7].Split(brakets);
                            if (destNumbers2.Length == 1 || destNumbers2[1] != destNumbers[1] ||
                                !_onlyDigits(columns[3]))  // не нашлась строка с тем же набранным номером
                                                 continue; // ну тогда не знаю куда она ее заперла
                        }
                    }
                    int lineNumber = int.Parse(columns[3]);
                    mainFormDataSet.Calls.AddCallsRow(internalNumber, timeStamp,
                                                      duration, lineNumber, destNumbers[1]);
                }

            }
            this.Validate();
            this.callsTableAdapter.Update(this.mainFormDataSet.Calls);
            this.callsTableAdapter.Fill(this.mainFormDataSet.Calls);
    }

        private void BtLoadToCallsClick(object sender, EventArgs e)
        {
            openLogFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openLogFile.FileName = "";
            if (openLogFile.ShowDialog() == DialogResult.OK)
            {
                LogParsing(openLogFile.FileName); // @"calls.txt"
            }
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btClearCalls_Click(object sender, EventArgs e)
        {
            var Form = new ClearCallsForm();
            Form.ShowDialog();
        }

    }
}
